package com.baidu.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.baidu.basic.DateUtils;
import com.baidu.emus.ClientType;
import com.baidu.model.MyTB;
import com.baidu.vo.ReplyInfo;
import com.jfinal.kit.StrKit;

/**
 * 签到工具类
 * @author iicm
 * 2016-1-19 10:17
 */
public class BaiDuApi {
	
	public static final BaiDuApi api = new BaiDuApi();
	
	private HttpClientUtil bc = HttpClientUtil.getInstance();
	
	//在这里定义百度相关的url
	private static final String BAIDU_URL = "http://www.baidu.com";//百度首页
	private static final String TOKEN_GET_URL = "https://passport.baidu.com/v2/api/?getapi&tpl=mn&apiver=v3&class=login&logintype=dialogLogin";//登陆token
	private static final String LOGIN_POST_URL = "https://passport.baidu.com/v2/api/?login";//登陆 post url
	private static final String TIEBA_GET_URL = "http://tieba.baidu.com";//贴吧地址
	private static final String TBS_URL = "http://tieba.baidu.com/dc/common/tbs";//tbs 获取随机参数（好多请求用到）
	private static final String USER_INFO_GET_URL = "http://tieba.baidu.com/f/user/json_userinfo";//获取用户json信息
//	private static final String WENKU_SIGN_URL = "http://wenku.baidu.com/task/submit/signin";
	private static final String MY_LIKE_URL = "http://tieba.baidu.com/f/like/mylike";//我喜欢的贴吧 url
	private static final String SIGN_POST_URL = "http://c.tieba.baidu.com/c/c/forum/sign";//签到 post url
	public static final String CAPTCHA_IMG = "https://passport.baidu.com/cgi-bin/genimage";//验证码图片地址
	public static final String REPLY_POST_URL  = "http://c.tieba.baidu.com/c/c/post/add";//贴吧回帖post url
	public static final String DEL_POST_URL  = "http://c.tieba.baidu.com/c/c/bawu/delthread";//删帖post url
	public static final String BAWU_POST_URL  = "http://c.tieba.baidu.com/c/u/bawu/listreason";//获取封禁列表
	public static final String PRISION_POST_URL  = "http://c.tieba.baidu.com/c/c/bawu/commitprison";//封禁用户
	public static final String INFO_GET_URL  = "http://www.baidu.com/p";//百度个人资料（获取贴吧头像）
	public static final String HEAD_GET_URL  = "http://himg.bdimg.com/sys/portrait/item";//（获取贴吧头像地址）
	public static final String BAIDUTIME_GET_URL  = "http://open.baidu.com/special/time/";//获取百度服务器时间
	public static final String TULING_POST_URL  = "http://www.tuling123.com/openapi/api";//图灵api
	public static final String TBAT_POST_URL  = "http://c.tieba.baidu.com/c/u/feed/";//贴吧@、回复
	public static final String FLOOR_POST_URL  = "http://c.tieba.baidu.com/c/f/pb/floor";//楼层
	public static final String BDUSS  = "plZHNSbWh2MzR0Nn5GVGpuanFBMnBFLVRxRzZ5Ykh-eE5-Nzl5TlBhVlNjTkZXQVFBQUFBJCQAAAAAAAAAAAEAAACaEH8JwZWRVF~Ex7PBxKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFLjqVZS46lWeU";
	/**
	 * 获取cookie
	 * @throws Exception 
	 */
	public Map<String, Object> getBduss(String userName, String password) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		String bduss = "";
		TestUtil.systemOutPrintln("准备登录 . :"+userName);
		// 预登录，获取cookie以便获取token.
		bc.execute(BAIDU_URL,null,null);
		String token = this.token();
		TestUtil.systemOutPrintln("正在登录。");
		HttpResponse response = bc.execute(LOGIN_POST_URL, null, produceFormEntity(userName,password,token,null,null));
		String result = EntityUtils.toString(response.getEntity());
		TestUtil.systemOutPrintln(result);
		String statusCode = StrUtil.substring(result, "error=", "'");
		TestUtil.systemOutPrintln("百度返回的状态码：" + statusCode);
		// 自动识别验证码。
		// tools.autoCode(codestring);
		EntityUtils.consume(response.getEntity());
		TestUtil.systemOutPrintln(result);
		TestUtil.systemOutPrintln("--------------------------------");
		if(!checkLogin()){
			TestUtil.systemOutPrintln("登录异常或频繁，需要验证码，codeString为：" + StrUtil.substring(result, "codestring=", "&"));
			TestUtil.systemOutPrintln("登录结果:" + userName + " 登录失败.");
			map.put("status", -1);
			map.put("message", "需要验证码");
			map.put("bduss", null);
			map.put("imgUrl", CAPTCHA_IMG+"?"+StrUtil.substring(result, "codestring=", "&"));
			return map;
		}else{
			TestUtil.systemOutPrintln("登录结果:" + " 登录成功.");
			List<Cookie> list = bc.getCookieStore().getCookies();
			for (Cookie cookie : list) {
				if(cookie.getName().equals("BDUSS")){
					bduss = cookie.getValue();
				}
			}
			map.put("status", 200);
			map.put("message", "获取成功");
			map.put("bduss", bduss);
			map.put("imgUrl", null);
			return map;
		}
	}
	
	/**
	 * 获取登陆token
	 * @return
	 * @throws Exception
	 */
	public String token() throws Exception{
		String token = null;
		HttpResponse response = bc.execute(TOKEN_GET_URL,null,null);
		String str = EntityUtils.toString(response.getEntity());
		Pattern pattern = Pattern.compile("token\" : \"(.*?)\"");
		Matcher matcher = pattern.matcher(str);
		if(matcher.find()){
			token = matcher.group(1);
		}
		return token;
	}
	/**
	 * 检验帖子id
	 * @param arr 
	 * @return 0 验证通过，-1 帖子所在的贴吧未关注，-2贴吧没有这个帖子 -3帖子不存在
	 * @throws Exception
	 */
	public Integer checkT(String bduss, String url, String fid) throws Exception{
		String isLike = null;
		String fid2 = null;
		HttpResponse response = bc.execute(url,bduss,null);
		String str = EntityUtils.toString(response.getEntity());
		Pattern pattern = Pattern.compile("islike: '(.*?)'");
		Matcher matcher = pattern.matcher(str);
		if(str.contains("page404")){
			return -3;
		}
		if(matcher.find()){
			isLike = matcher.group(1);
		}
		Pattern fidPattern = Pattern.compile("fid: '(.*?)'");
		Matcher fidMatcher = fidPattern.matcher(str);
		if(fidMatcher.find()){
			fid2 = fidMatcher.group(1);
		}
		if("1".equals(isLike)){
			if(!fid2.equals(fid)){
				return -2;
			}
		}else if("0".equals(isLike)){
			return -1;
		}
		return 0;
	}
	
	private boolean checkLogin() throws Exception{
		HttpResponse response = bc.execute(BAIDU_URL,null,null);
		boolean res = false;
		String content = EntityUtils.toString(response.getEntity());
		if(!content.contains("登录")){
			res = true;
		}
		EntityUtils.consume(response.getEntity());
		return res;
	}
	
	// 登录POST参数
	private List<NameValuePair> produceFormEntity(String userName, String password, String token, String verifyCode, String codeString) throws UnsupportedEncodingException{
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("tt", ""+System.currentTimeMillis()));
		list.add(new BasicNameValuePair("tpl", "mn"));
		list.add(new BasicNameValuePair("token", token));
		list.add(new BasicNameValuePair("isPhone", ""));
		list.add(new BasicNameValuePair("username", userName));
		list.add(new BasicNameValuePair("password", password));
		list.add(new BasicNameValuePair("verifycode", verifyCode));
		list.add(new BasicNameValuePair("codestring", codeString));
		return list;
	}
	
	/**
	 * 获取我喜欢的贴吧
	 * @throws Exception 
	 */
	public List<MyTB> getMyLikedTB(String bduss) throws Exception{
		List<MyTB> list = new ArrayList<MyTB>();
		HttpResponse response = bc.execute(MY_LIKE_URL, bduss, null);
		String result = EntityUtils.toString(response.getEntity());
		Pattern pattern = Pattern.compile("<tr><td>.+?</tr>");
		Matcher matcher = pattern.matcher(result);
		while(matcher.find()){
			Document doc1 = Jsoup.parse(matcher.group());
			Elements link  = doc1.children();
			for (Element element : link) {
				MyTB tb = new MyTB();
				String ex = element.select(".cur_exp").first().text();//当前经验
				String lv = element.select(".like_badge_lv").first().text();//等级
				String lvName = element.select(".like_badge_title").first().html();//等级名称
				String fid = element.select("span").last().attr("balvid");//贴吧ID（签到关键参数）
				String tbName = element.select("a").first().text();//贴吧名称
				//String url = TIEBA_GET_URL +  URLDecoder.decode(element.select("a").first().attr("href"),"utf-8");//贴吧地址
				String url = TIEBA_GET_URL + element.select("a").first().attr("href");//贴吧地址
				tb.set("fid", Integer.parseInt(fid));
				tb.set("name", tbName);
				tb.set("href", url);
				tb.set("ex", ex);
				tb.set("level", lv);
				tb.set("levelName", lvName);
				tb.set("isHuLue", false);
				tb.set("isDeleted", false);
				list.add(tb);
			}
		}
		return list;
	}
	
	/**
	 * 获取tbs
	 * @throws Exception 
	 */
	public String getTbs(String bduss) throws Exception{
		HttpResponse response = bc.execute(TBS_URL,bduss,null);
		return (String) JsonUtil.getInfo("tbs", EntityUtils.toString(response.getEntity()));
	}
	
	/**
	 * 获取用户信息
	 * @param cookie
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getUserInfo(String bduss) throws Exception{
		HttpResponse response = bc.execute(USER_INFO_GET_URL, bduss, null);
		String result = EntityUtils.toString(response.getEntity());
		try {
            if("0".equals(JsonUtil.getInfo("no", result).toString())){
            	return (Map<String, Object>) JsonUtil.getInfo("data", result);
            }
        } catch (Exception e) {
            return null;
        }
		return null;
	}
	
	/**
	 * 获取用户头像URL
	 * @param cookie
	 * @return
	 * @throws Exception
	 */
	public String getHeadImg(String bduss, String userName) throws Exception{
		HttpResponse response = bc.execute(INFO_GET_URL + "/" + userName, bduss, null);
		String result = EntityUtils.toString(response.getEntity());
		return HEAD_GET_URL + "/" + StrUtil.substring(result, "'portrait' : '", "'")+".jpg";
	}
	
	/**
	 * 执行签到
	 * @param tbName 贴吧名称
	 * @param tbId 贴吧fid
	 * @throws Exception
	 */
	@SuppressWarnings({ "resource", "unchecked" })
	public MyTB signDo(MyTB tb, String bduss) throws Exception{
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		//list.add(new BasicNameValuePair("BDUSS", substring(cookie, "BDUSS=", ";")));
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("_client_id", "03-00-DA-59-05-00-72-96-06-00-01-00-04-00-4C-43-01-00-34-F4-02-00-BC-25-09-00-4E-36"));
		list.add(new BasicNameValuePair("_client_type", "4"));
		list.add(new BasicNameValuePair("_client_version", "1.2.1.17"));
		list.add(new BasicNameValuePair("_phone_imei", "540b43b59d21b7a4824e1fd31b08e9a6"));
		list.add(new BasicNameValuePair("fid",  new Formatter().format("%d",tb.getInt("fid")).toString()));
		list.add(new BasicNameValuePair("kw", tb.getStr("name")));
		list.add(new BasicNameValuePair("net_type", "3"));
		list.add(new BasicNameValuePair("tbs", getTbs(bduss)));
		String signStr = "";
		for (NameValuePair nameValuePair : list) {
			signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
		}
		signStr += "tiebaclient!!!";
		list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
		
		HttpResponse response = bc.execute(SIGN_POST_URL, bduss, list);
        String result = EntityUtils.toString(response.getEntity());
        String code = (String) JsonUtil.getInfo("error_code", result);
        String msg = (String) JsonUtil.getInfo("error_msg", result);
        Map<String, String> map = (Map<String, String>) JsonUtil.getInfo("user_info", result);
        if("0".equals(code)){//签到成功
            tb.set("exp", map==null?"0":map.get("sign_bonus_point"));
            tb.set("countSignNum", map==null?0:Integer.parseInt(map.get("cont_sign_num")));
            tb.set("signTime", DateUtils.realTime("Asia/Shanghai"));
            tb.set("error_msg", "签到成功");
            //tb.set("signTime", Integer.parseInt(map.get("sign_time"))*1000);
        }else if("160002".equals(code)){//已经在其他地方签到 更新签到时间
            tb.set("signTime", DateUtils.realTime("Asia/Shanghai"));
        }else if("340006".equals(code)){//贴吧本身原因导致的签到失败，如贴吧被封，自动忽略该贴吧
            tb.set("isHuLue", 1);
        }
        if(StrKit.notBlank(msg)){
            tb.set("error_msg", new String(msg));
        }
        tb.set("code", code);
        return tb;
	}
	
	/**
	 * 获取贴吧首页帖子tid列表
	 * @param bduss
	 * @param tbName
	 * @param replyNum 定义标志 根据回复数筛选（回复为0的帖子，抢二楼专用）
	 * @return 帖子tid 数组
	 * @throws Exception
	 */
	public List<String> getIndexTList(String bduss, String tbName, Integer replyNum) throws Exception{
		List<String> list = new ArrayList<String>();
		HttpResponse response = bc.execute(TIEBA_GET_URL + "/f?kw=" + tbName + "&fr=index", bduss, null);
		String result = EntityUtils.toString(response.getEntity());
		if(StrKit.notBlank(result) && response.getStatusLine().getStatusCode() == 200){
			Document doc = Jsoup.parse(result);
			Elements link  = doc.getElementsByAttributeValue("class", "j_th_tit"); //帖子链接（获取tid）
			Elements data  = doc.getElementsByAttributeValueMatching("class", "j_thread_list.* clearfix"); //回复数,是否置顶 data-field
			for (int i = 0; i < link.size(); i++) {
				Element element = link.get(i);
				Integer reply= (Integer) JsonUtil.getInfo("reply_num",data.get(i).attr("data-field"));
				Object isTop = JsonUtil.getInfo("is_top",data.get(i).attr("data-field"));
				if(isTop != null && ("1".equals(isTop.toString()) || "true".equals(isTop.toString()))){//是置顶贴，默认不回复 所以在这里过滤掉
					continue;
				}
				if(replyNum != null && replyNum == 0){
					if(reply == 0){
						list.add(element.attr("href").substring(3));
					}
				}else{
					list.add(element.attr("href").substring(3));
				}
			}
		}
		TestUtil.systemOutPrintln(list.size());
		return list;
	}
	
	/**
	 * 删帖
	 * @param bduss
	 * @param fid 贴吧fid
	 * @param z 帖子tid
	 * @param tbName 贴吧名称
	 * @throws Exception
	 */
	public void delT(String bduss, String fid, String z, String tbName) throws Exception{
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("_client_id", "wappc_1451451147094_870"));
		list.add(new BasicNameValuePair("_client_type", "2"));
		list.add(new BasicNameValuePair("_client_version", "6.2.2"));
		list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
		list.add(new BasicNameValuePair("fid", fid));
		list.add(new BasicNameValuePair("is_vipdel", "0"));
		list.add(new BasicNameValuePair("tbs", getTbs(bduss)));
		list.add(new BasicNameValuePair("word", tbName));//贴吧
		list.add(new BasicNameValuePair("z", z));//帖子id
		String signStr = "";
		for (NameValuePair nameValuePair : list) {
			signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
		}
		signStr += "tiebaclient!!!";
		list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
		HttpResponse response = bc.execute(DEL_POST_URL, bduss, list);
		String result = EntityUtils.toString(response.getEntity());
		TestUtil.systemOutPrintln(result);

	}
	
	/**
	 * 获取封禁原因列表和用户信息
	 * @param bduss
	 * @param fid 贴吧fid
	 * @param userId 用户id
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<String> getPrisionReasionList(String bduss, String fid, String userId) throws Exception{
		List<String> reasonList = null;
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("_client_id", "wappc_1451451147094_870"));
		list.add(new BasicNameValuePair("_client_type", "2"));
		list.add(new BasicNameValuePair("_client_version", "6.2.2"));
		list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
		list.add(new BasicNameValuePair("forum_id", fid));//贴吧id
		list.add(new BasicNameValuePair("user_id", userId));//用户id
		String signStr = "";
		for (NameValuePair nameValuePair : list) {
			signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
		}
		signStr += "tiebaclient!!!";
		list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
		HttpResponse response = bc.execute(BAWU_POST_URL, bduss, list);
		String result = EntityUtils.toString(response.getEntity());
		String code = (String) JsonUtil.getInfo("error_code", result);
		if("0".equals(code)){
			reasonList = (List<String>) JsonUtil.getInfo("reason", result);
		}
		TestUtil.systemOutPrintln(reasonList.toString());
		return reasonList;
	}
	
	/**
	 * 封禁用户
	 * @param bduss
	 * @param fid 贴吧fid
	 * @param userId 用户id
	 * @throws Exception
	 */
	public void commitprison(String bduss, String fid, String userName, String tbName, String tid) throws Exception{
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("_client_id", "wappc_1451451147094_870"));
		list.add(new BasicNameValuePair("_client_type", "2"));
		list.add(new BasicNameValuePair("_client_version", "6.2.2"));
		list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
		list.add(new BasicNameValuePair("day", "10"));//吧务封禁一天
		list.add(new BasicNameValuePair("fid", fid));//贴吧id
		list.add(new BasicNameValuePair("ntn", "banid"));//未知
		list.add(new BasicNameValuePair("reason", "大量散布广告，发表交易帖，屡教不改，给予封禁处罚。"));//封禁原因
		list.add(new BasicNameValuePair("tbs", getTbs(bduss)));//tbs
		list.add(new BasicNameValuePair("un", userName));//封禁的用户名称
		list.add(new BasicNameValuePair("word", tbName));//贴吧名称
		list.add(new BasicNameValuePair("z", tid));//帖子id
		String signStr = "";
		for (NameValuePair nameValuePair : list) {
			signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
		}
		signStr += "tiebaclient!!!";
		list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
		HttpResponse response = bc.execute(PRISION_POST_URL, bduss, list);
		String result = EntityUtils.toString(response.getEntity());
		TestUtil.systemOutPrintln(result);
		
	}
	
	/**
	 * 回帖
	 * @param bduss
	 * @param tid 帖子id
	 * @param fid 贴吧id
	 * @param tbName 贴吧名称
	 * @param content 回复内容
	 * @param clientType 模拟的哭护短类型
	 * @return
	 */
	public String reply(String bduss, String tid, String fid, String tbName, String content, Integer clientType) throws Exception{
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		if(clientType == 0){//随机选择一种方式
			ClientType[] arr = ClientType.values();
			Random random= new Random();
			int  num = random.nextInt(arr.length);
			clientType = arr[num].getCode();
		}
		list.add(new BasicNameValuePair("_client_id", "wappc_1450693793907_490"));
		list.add(new BasicNameValuePair("_client_type", clientType.toString()));
		list.add(new BasicNameValuePair("_client_version", "6.2.2"));
		list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
		list.add(new BasicNameValuePair("anonymous", "0"));
		list.add(new BasicNameValuePair("content", content));
		list.add(new BasicNameValuePair("fid", fid));
		list.add(new BasicNameValuePair("kw", tbName));
		list.add(new BasicNameValuePair("net_type", "3"));
		list.add(new BasicNameValuePair("tbs", getTbs(bduss)));
		list.add(new BasicNameValuePair("tid", tid));
		list.add(new BasicNameValuePair("title", ""));
		String signStr = "";
		for (NameValuePair nameValuePair : list) {
			signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
		}
		signStr += "tiebaclient!!!";
		list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
		HttpResponse response = bc.execute(REPLY_POST_URL, bduss, list);
		String result = EntityUtils.toString(response.getEntity());
		TestUtil.systemOutPrintln(result);
		String code = (String) JsonUtil.getInfo("error_code", result);
		String msg = (String) JsonUtil.getInfo("msg", result);
		if("0".equals(code)){//回帖成功
			return "回帖成功";
		}
		return StrKit.notBlank(msg)?msg:"回帖失败";
	}
	
	public Long getBaiDuTime() throws Exception{
		HttpResponse response = bc.execute(BAIDUTIME_GET_URL, null, null);
		String result = EntityUtils.toString(response.getEntity());
		String bdTime = StrUtil.substring(result, "window.baidu_time(", ")");
		Long time = StrKit.isBlank(bdTime)?0L:Long.parseLong(bdTime);
		return time;
	}
	
	/**
	 * 查询艾特/回复 信息
	 * @param bduss
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public List<ReplyInfo> getmsg (String bduss, String type) throws Exception{
	    List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("BDUSS", bduss));
        list.add(new BasicNameValuePair("_client_id", "wappc_1450693793907_490"));
        list.add(new BasicNameValuePair("_client_type", "2"));
        list.add(new BasicNameValuePair("_client_version", "6.2.2"));
        list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
        list.add(new BasicNameValuePair("net_type", "3"));
        list.add(new BasicNameValuePair("pn", "1"));
        String signStr = "";
        for (NameValuePair nameValuePair : list) {
            signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
        }
        signStr += "tiebaclient!!!";
        list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
        HttpResponse response = bc.execute(TBAT_POST_URL + type+ "me", bduss, list);
        String result = EntityUtils.toString(response.getEntity());
        return JSON.parseArray(JsonUtil.getInfo(type + "_list", result).toString(), ReplyInfo.class);
	}
	
	/**
	 * 获取楼层pid
	 * @throws Exception 
	 */
	public String floorPid (String bduss, String tid, String pid) throws Exception{
	    List<NameValuePair> list = new ArrayList<NameValuePair>();
	    list.add(new BasicNameValuePair("BDUSS", bduss));
	    list.add(new BasicNameValuePair("_client_id", "wappc_1450693793907_490"));
	    list.add(new BasicNameValuePair("_client_type", "2"));
	    list.add(new BasicNameValuePair("_client_version", "6.2.2"));
	    list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
	    list.add(new BasicNameValuePair("kz", tid));
	    list.add(new BasicNameValuePair("net_type", "3"));
	    list.add(new BasicNameValuePair("spid", pid));
	    list.add(new BasicNameValuePair("tbs", getTbs(bduss)));
	    String signStr = "";
	    for (NameValuePair nameValuePair : list) {
	        signStr += new Formatter().format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()).toString();
	    }
	    signStr += "tiebaclient!!!";
	    list.add(new BasicNameValuePair("sign", MD5Util.toMd5(signStr).toUpperCase()));
	    HttpResponse response = bc.execute(FLOOR_POST_URL, bduss, list);
	    String result = EntityUtils.toString(response.getEntity());
	    System.out.println(result);
	    return result;
	}

	/**
	 * 调用图灵api
	 * @throws Exception
	 */
	public String tuLing() throws Exception{
	    List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("key", "eff68b521fdcf98373c1dac1af7ea55c"));
        list.add(new BasicNameValuePair("info", "心情不好"));
        list.add(new BasicNameValuePair("userid", "abc123"));
        HttpResponse response = bc.execute(TULING_POST_URL, null, list);
        return EntityUtils.toString(response.getEntity());
	}
	
	public static void main(String[] args) throws Exception {
	    BaiDuApi.api.getmsg(BDUSS,"at");
	 //   BaiDuApi.api.tuLing();
		/*Long baiduTime = BaiDuApi.api.getBaiDuTime();
		SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
		if(Integer.parseInt(sdf.format(new Date(baiduTime)))>=235900){
			Thread t = new Thread(new Runnable(){  
	            public void run(){  
	            	
	            }});  
	        t.start();
		}*/
		//SignUtil.dao.getHeadImg("lpHV2FTeld4ZC1DbUdlbHp6VzY1Z1hxTlFEZEoya2NsbjhJRDhIZkd-WVJUbjVXQVFBQUFBJCQAAAAAAAAAAAEAAACaEH8JwZWRVF~Ex7PBxKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHBVlYRwVZWT", "尋找她旳身影");
		//SignUtil.dao.getPrisionReasionList("lpHV2FTeld4ZC1DbUdlbHp6VzY1Z1hxTlFEZEoya2NsbjhJRDhIZkd-WVJUbjVXQVFBQUFBJCQAAAAAAAAAAAEAAACaEH8JwZWRVF~Ex7PBxKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHBVlYRwVZWT",
//				"4177852", "159322266");
		/*SignUtil.dao.commitprison("lpHV2FTeld4ZC1DbUdlbHp6VzY1Z1hxTlFEZEoya2NsbjhJRDhIZkd-WVJUbjVXQVFBQUFBJCQAAAAAAAAAAAEAAACaEH8JwZWRVF~Ex7PBxKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHBVlYRwVZWT",
				 "159322266", "日光浴01", "", "4241262695");*/
		//SignUtil.dao.getIndexTList(bduss,"阿城",0);
		//Random r = new Random();
		//TestUtil.systemOutPrintln(r.nextInt(5));
//		SignUtil.dao.reply("lpHV2FTeld4ZC1DbUdlbHp6VzY1Z1hxTlFEZEoya2NsbjhJRDhIZkd-WVJUbjVXQVFBQUFBJCQAAAAAAAAAAAEAAACaEH8JwZWRVF~Ex7PBxKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHBVlYRwVZWT", "1396832551", "282280", "姜敏京", "大爱姜敏京~~我女神", 1);
		//sign.signDo("魔兽世界", 73787, cookie);
//		TestUtil.systemOutPrintln(sign.getUserInfo(bduss3).get("session_id"));
//		ssign.getMyLikedTB(bduss);
//		TestUtil.systemOutPrintln(sign.getTbs(bduss3));
		//TestUtil.systemOutPrintln(sign.getUserInfo(cookie).get("user_name_weak"));
		//TestUtil.systemOutPrintln(substring(cookie,""));
		//TestUtil.systemOutPrintln(sign.getCookie("491497199@qq.com", "003675as,."));
		//TestUtil.systemOutPrintln(substring(sign.getUserInfo(cookie),"session_id=",","));
		//sign.signDo();
	}
	
}
